# coding=utf-8
# __author__ = "James Zhang"
# !/usr/bin/python
# -*- coding: utf-8 -*-
import socket
import tornado.web
import tornado.websocket
import tornado.httpserver
import tornado.ioloop
import tornado.options
from tornado.web import URLSpec as _Url
from tornado.options import define, options
from tornado.netutil import bind_sockets
import functools


tornado.options.define("port", default=8000, help="run at given port.", type=int)
tornado.options.define("host", default='127.0.0.1', help="run at given host.", type=str)

clients = set()


class IndexPageHandler(tornado.web.RequestHandler):
    def get(self):
        # print(self.reverse_url('websocket'))    # 反向查询url
        self.render('index.html')


class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def check_origin(self, origin):
        return True

    def open(self, *args, **kwargs):
        print('start..........', clients)
        clients.add(self)
        pass

    def on_message(self, message):
        for client in clients:
            client.write_message("message was: " + message)

    def on_close(self):
        clients.remove(self)
        print("close websocket!")


class HelloModule(tornado.web.UIModule):
    def render(self, *args, **kwargs):
        return "<h1>I am yxx and this an information from module hello!</h1>"


class BookModule(tornado.web.UIModule):
    def render(self, book_name):
        """返回输出
            :param book_name:
        """
        search_api = r'http://api/douban.com/v2/book/search?q='
        search_url = search_api + book_name
        book_info = search_url
        # render_string方法把一个对象渲染到一个模板当中去.
        return self.render_string('module/book.html', book=book_info)

    def embedded_css(self):
        """返回css字符串,并嵌入到模板当中
        """
        return """.book{background-color: #f5f5f5}
                  .book_body{color: red}"""

    def embedded_javascript(self):
        """返回js字符串,并嵌入到模板当中
        """
        return """document.write(\"hi!\")"""

    def html_body(self):
        """返回HTML字符串,并嵌入到</body>标签之后
        """
        return """<script>document.write("Hello!")</script>"""

    def html_head(self):
        """返回HTML字符串,并嵌入到</head>标签中
        """
        return """<script src="/static/js/jquery-1.8.3.min.js"></script>"""

    def css_files(self):
        """returns a list of CSS files required by this module.

        If the return values are relative paths, they will be passed to
        `RequestHandler.static_url`; otherwise they will be used as-is.
        """
        return [r"/static/css/TPForm.css", r"/static/css/TPForm.css", r"/static/css/TPForm.css"]

    def javascript_files(self):
        """return an HTML string that will be put in the <head/>
        element.
        """
        return r"/static/js/TPForm.js"


class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            _Url(r'^/', IndexPageHandler, name='index'),        # name的值必须唯一
            _Url(r'^/ws', WebSocketHandler, name='websocket'),
        ]
        settings = {
            'template_path': '../templates',
            "static_path": '../static',
            'debug': True,
            'ui_modules': {'Hello': HelloModule, 'Book': BookModule},
            }
        tornado.web.Application.__init__(self, handlers, **settings)


if __name__ == "__main__":
    options.parse_command_line()
    ws_app = Application()
    http_server = tornado.httpserver.HTTPServer(ws_app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()
